package com.forum.service.impl;

import com.forum.constant.MessageConstant;
import com.forum.constant.StatusConstant;
import com.forum.dto.UserDTO;
import com.forum.dto.UserForgotDTO;
import com.forum.dto.UserPageQueryDTO;
import com.forum.entity.User;
import com.forum.entity.UserInfo;
import com.forum.exception.*;
import com.forum.mapper.FavoritesMapper;
import com.forum.mapper.ThreadsMapper;
import com.forum.mapper.UserMapper;
import com.forum.result.PageResult;
import com.forum.result.Result;
import com.forum.service.UserService;
import com.forum.vo.UserInfoStatisticsVO;
import com.forum.vo.UserInfoVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ThreadsMapper threadsMapper;
    @Autowired
    private FavoritesMapper favoritesMapper;
    @Override
    @Transactional
    public Result register(UserDTO userDTO) {
        User user = userMapper.queryUserByUserName(userDTO.getUsername());
        log.info("查询的结果：{}",user);
        // 1.先判断账号是否存在
        if (user != null){
            // 2.存在则返回
            return Result.error("用户已存在");
        }
        // 3.不存在则注册
        // 3.将密码加密存入数据库
        userDTO.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));
        // 添加默认角色，用户
        userDTO.setRole(MessageConstant.ROLE_USER);

        userMapper.creatUser(userDTO);
        User user1 = userMapper.queryUserByUserName(userDTO.getUsername());

        log.info("用户注册成功：{}",user1);

        UserInfo userInfo = UserInfo
                .builder()
                .userId(user1.getId())
                .status(StatusConstant.ENABLE)
                .sex(userDTO.getSex())
                .build();

        userMapper.insertStatus(userInfo);

        return Result.success("注册成功");
    }

    @Override
    public User login(UserDTO userDTO) {
        // 1.判断账号是否存在
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        User user = userMapper.queryUserByUserName(username);
        if (user == null){
            throw new AccountNotFoundException(MessageConstant.USER_NOT_FOUND);
        }
        // 2.判断密码是否正确
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())){
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        return user;
    }

    @Override
    @Transactional
    public void DeleteById(List<Long> ids) {
        // 1.用户未被禁用不能删除
        Long count = userMapper.queryByIds(ids);
        log.info("查询到的数据有多少条：{}",count);
        if (count > 0){
            throw new UserStatusEnabled(MessageConstant.USER_ENABLED);
        }
        // 批量删除
        userMapper.deleteByIds(ids);

    }

    @Override
    public PageResult pageQuery(UserPageQueryDTO userPageQueryDTO) {
        // 开始分页查询
        PageHelper.startPage(userPageQueryDTO.getPage(),userPageQueryDTO.getPageSize());
        Page<User> page = userMapper.pageQuery(userPageQueryDTO);
        log.info("查询出来的结果:{}",page);
        long total = page.getTotal();
        List<User> records = page.getResult();
        return new PageResult(total,records);
    }

    @Override
    public void updateByIdStatus(Long id, Integer status) {
        // 根据id修改用户状态
        userMapper.updateByIdStatus(id,status);
    }

    @Override
    public void updateByUsername(UserForgotDTO userForgotDTO) {
        String username = userForgotDTO.getUsername();
        // 1.判断账号是否存在
        User user = userMapper.queryUserByUserName(username);
        String name = user.getName();
        if (user == null ){
            throw new UserNotLoginException(MessageConstant.USER_NOT_FOUND);
        }
        // 2.账号存在判断用户名是否存在
        log.info("用户名：{}",name);
        if (!name.equals(name)){
            throw new UserNotFoundName(MessageConstant.USER_NOT_NAME);
        }
        // 3.用户存在则修改密码
        // 3.1.先将密码初始为123456
        Long userId = user.getId();
        // 3.2.将第一次输入的密码和第二次输入的密码做对比判断是否一致
        if (!userForgotDTO.getPassword().equals(userForgotDTO.getAgainPassword())){
            throw new PasswordErrorException(MessageConstant.PASSWORD_DIFFERENT);
        }
        User build = User.builder()
                .id(userId)
                .password(DigestUtils.md5DigestAsHex(userForgotDTO.getPassword().getBytes()))
                .build();
        // 3.3.如果两次密码一致则修改密码
        userMapper.updateById(build);
    }

    @Override
    public void updateById(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        userMapper.updateById(user);
    }

    @Override
    public UserInfoVO getById(Long id) {
        log.info("查询用户id：{}",id);
        UserInfoVO userInfo = userMapper.getUserInfoById(id);
        return userInfo;
    }

    @Override
    @Transactional
    public UserInfoStatisticsVO getUserStatistics(Long id) {
        UserInfoStatisticsVO userInfoStatisticsVO = new UserInfoStatisticsVO();
        // 查询用户所发布数量和获赞数
        UserInfoStatisticsVO releaseLikeCount= threadsMapper.releaseLikeCount(id);
        // 查询用户所收藏数量
        Integer collection = favoritesMapper.query(id);
        // 查询用户详细信息
        UserInfoVO userInfoVO = userMapper.getUserInfoById(id);
        BeanUtils.copyProperties(releaseLikeCount, userInfoStatisticsVO);
        BeanUtils.copyProperties(userInfoVO, userInfoStatisticsVO);

        userInfoStatisticsVO.setCollection(collection);
        return userInfoStatisticsVO;
    }

    /**
     * 修改用户背景图
     *
     * @param id
     * @param backgroundUrl
     */
    @Override
    public void putBackground(Long id, String backgroundUrl) throws IOException {
        // 1.先查询用户原来是否有背景
        String url = userMapper.getbackgroundUrl(id);
        if (url == null){
            // 2.没有则直接添加
            userMapper.updateByIdBackground(id,backgroundUrl);
        }else {
            // 3.有则先删除原来的背景，再添加新的
            log.info("用户原来的背景图：{}",url);
            url = url.replace("http://localhost:8899/upload/","");
            String filePath = "forum-server/src/main/resources/upload/"+url;
            log.info("删除的图片路径：{}",filePath);
            boolean b = Files.deleteIfExists(Paths.get(filePath));
            log.info("删除结果：{}",b);
            userMapper.updateByIdBackground(id,backgroundUrl);

        }
    }
}
